﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Micrhard.FMCG.Server.Interface;
using Microhard.Core.DBUtility;
using Micrhard.FMCG.Server.DataAccess;
using Micrhard.FMCG.Server.DTO;
using Micrhard.FMCG.Server.Msg;
using Microhard.Core;
using Micrhard.FMCG.Server.Models;

namespace Micrhard.FMCG.Server.Impl
{
    public class NoticeImpl : INotice
    {
        public Microhard.Core.DBUtility.ExecutedResult Add(Models.NoticeModel model)
        {
            ExecutedResult rtn = new ExecutedResult();
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var op = model.ToEntity();
            op.CreateTime = DateTime.Now;

            try
            {
                //获得当前产品关联的company
                var emp = db.Employees.Single(w => w.UserName == scope.CurrentUserName);
                op.CompanyID = emp.CompanyID;
                model.CompanyID = emp.CompanyID.Value;
                op.PubEmployeeID = emp.EmployeeID;
                //没有选择，则默认全体发送
                if (model.RecEmployees == null || model.RecEmployees.Count == 0)
                {
                    var np = (from e in db.Employees
                              where e.CompanyID == emp.CompanyID
                              select e.EmployeeID).ToList();
                    np.ForEach(n =>
                    {
                        op.NoticeRecScopes.Add(new NoticeRecScope
                        {
                            NoticeScopeID = Guid.NewGuid(),
                            NoticeID = op.NoticeID,
                            RecEmployeeID = n
                        });
                    });
                }
                else
                {
                    foreach (var r in model.RecEmployees)
                    {
                        op.NoticeRecScopes.Add(new NoticeRecScope
                        {
                            NoticeScopeID = Guid.NewGuid(),
                            NoticeID = op.NoticeID,
                            RecEmployeeID = r.EmployeeID
                        });
                    }
                }

                db.Notices.AddObject(op);
                db.SaveChanges();
            }
            catch (System.Exception ex)
            {
                rtn.ErrorMsg.Add(DBOperationFailedStatus.AddFailed, NoticeMsg.AddFailed);
                Log.Error("INotice.Add", ex);
            }
            return rtn;
        }

        public Microhard.Core.DBUtility.ExecutedResult Update(Models.NoticeModel model)
        {
            throw new NotImplementedException();
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(List<Guid> ids)
        {
            ExecutedResult result = new ExecutedResult();
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var entity = db.Notices.Where(l => ids.Contains(l.NoticeID)).ToList();
            foreach (var e in entity)
            {
                var todelScope = e.NoticeRecScopes.ToList();
                foreach (var s in todelScope)
                {
                    db.NoticeRecScopes.DeleteObject(s);
                }
                db.Notices.DeleteObject(e);
            }
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed, CompanyMsg.DeleteFailed);
                Log.Error("INotice.Delete", ex);
            }
            return result;
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(Models.NoticeModel model)
        {
            throw new NotImplementedException();
        }

        public Models.NoticeModel GetModelByID(Guid id)
        {
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var model = db.Notices.SingleOrDefault(c => c.NoticeID == id);
            if (model != null)
            {
                return model.ToModel();
            }
            return null;
        }

        public Models.NoticeModel GetModelByModel(Models.NoticeModel model)
        {
            throw new NotImplementedException();
        }

        public List<Models.NoticeModel> Query(Models.NoticeModel Model, int pageIndex, int pageSize, out int totalCount)
        {
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var cmp = db.Employees.SingleOrDefault(e => e.UserName == this.scope.CurrentUserName).Company;
            IEnumerable<Notice> entities = from b in db.Notices
                                           where this.scope.PKID.Contains(b.NoticeID)
                                           select b;
            totalCount = entities.Count();
            var pagedEntities = entities.OrderByDescending(p => p.CreateTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            if (pagedEntities != null && pagedEntities.Count > 0)
                return pagedEntities.Select(m => m.ToModel()).ToList();
            return new List<NoticeModel>();
        }

        public List<Models.NoticeModel> Query(Models.NoticeModel Model)
        {
            throw new NotImplementedException();
        }

        public Microhard.Core.DBUtility.ScopeResult scope
        {
            set;
            get;
        }

        public List<NoticeModel> GetNoticesByWeixinOpenID(string weixinOpenID)
        {
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            return (from n in db.NoticeRecScopes
                    where n.Employee.WeixinOpenID == weixinOpenID
                    select n.Notice).ToList().Select(t => t.ToModel()).ToList();
        }
    }
}
